<template>
  <view class="container">
    <z-paging-swiper>
      <view slot="top">
        <u-navbar
          height="50"
          :is-back="false"
          :border-bottom="false"
          title="交易订单"
          title-size="36"
          title-color="#333"
        >
          <view style="padding: 0 20rpx" @click="$utils.goToUserCenter()">
            <u-icon name="close" size="30"></u-icon>
          </view>
        </u-navbar>
        <view class="tabsView">
          <u-tabs-swiper
            ref="uTabs"
            :list="tabsList"
            :current="current"
            @change="tabsChange"
            :is-scroll="false"
            :show-bar="false"
            active-color="#10A28F"
            swiper-width="750"
          >
          </u-tabs-swiper>
        </view>
        <u-gap height="20" bg-color="#F0F1F2"></u-gap>
      </view>
      <swiper
        class="swiperView"
        :current="scurrent"
        @transition="transition"
        @animationfinish="animationfinish"
      >
        <swiper-item v-for="(_sitem, sindex) in tabsList" class="swiperItem" :key="sindex">
          <z-paging
            ref="paging"
            v-model="itemList[sindex]"
            @query="queryList"
            :fixed="true"
            :auto="false"
            :auto-show-back-to-top="true"
            :empty-view-img="`${getImageUrl('empty.png')} `"
            empty-view-text="暂无订单数据~"
            :empty-view-img-style="imgStyle"
          >
            <view class="goodsItemView">
              <view
                class="itemView"
                v-for="(item, index1) in itemList[sindex]"
                :key="index1"
                @click="onOrderDetail(item)"
              >
                <view class="order-top dis-flex flex-y-center flex-y-between">
                  <view
                    class="dis-flex flex-y-center"
                    v-if="item.shop"
                    @click.stop.prevent="onShop(item.shop)"
                  >
                    <u-image
                      class="goods-img"
                      style="margin-right: 20rpx; border: 1rpx solid #999999"
                      :src="item.shop.logo"
                      width="60rpx"
                      height="60rpx"
                      border-radius="30"
                    ></u-image>
                    <text>{{ item.shop.name }}</text>
                  </view>
                  <view class="order-top-tip">
                    <text
                      v-if="item.type === 10"
                      style="color: black; font-weight: bold; font-size: 28rpx; margin-right: 20rpx"
                      >外卖</text
                    >
                    <text
                      v-if="item.reserveDate"
                      style="
                        color: #cb6501;
                        font-weight: bold;
                        font-size: 28rpx;
                        margin-right: 20rpx;
                      "
                      >预约</text
                    >
                    <text v-if="item.status === 10 || item.status === 20" style="color: orange">{{
                      item.statusName
                    }}</text>
                    <text v-else>{{ item.statusName }}</text>
                  </view>
                </view>
                <view class="layoutView">
                  <view class="order-goods" v-for="item2 in item.items" :key="item2.id">
                    <u-image
                      class="goods-img"
                      :src="item2.picUrl"
                      width="160rpx"
                      height="160rpx"
                      border-radius="10"
                    ></u-image>
                    <view class="orde-riget" style="flex: 1">
                      <view class="goods-title">
                        <text>{{ item2.spuName }}</text>
                      </view>
                      <view class="goods-speci dis-flex flex-x-baseline">
                        <text v-if="item2.properties && item2.properties.length > 0"
                          >{{ item2.properties[0].valueName }}
                        </text>
                        <text class="goodsNum" style="margin-left: 20rpx"
                          >{{ item2.count }}{{ item2.unitValue > 1 ? 'x' + item2.unitValue : ''
                          }}{{ item2.unitName || '' }}
                        </text>
                        <view class="flex-1"></view>
                        <text class="goodsNum" v-if="item2.weight"
                          >约{{ (item2.count * item2.weight * 1000).toFixed(0) }}克
                        </text>
                      </view>
                      <view class="goods-price" v-if="item2.afterSaleId">
                        <text>¥{{ (item2.price * 0.01).toFixed(2) }}</text>
                        <text
                          class="goods-refund"
                          v-if="
                            item2.afterSaleStatus === 10 ||
                            item2.afterSaleStatus === 20 ||
                            item2.afterSaleStatus === 30
                          "
                        >
                          退款进行中
                        </text>
                        <text class="goods-refund" v-else-if="item2.afterSaleStatus === 40">
                          等待平台退款
                        </text>
                        <text class="goods-refund" v-else-if="item2.afterSaleStatus === 50">
                          退款成功
                        </text>
                        <text class="goods-refund" v-else> 已终止退款</text>
                      </view>
                    </view>
                  </view>
                </view>
                <view class="price-total dis-flex flex-y-center flex-y-between">
                  <view>
                    <text>{{ item.payStatus ? '实付' : '应付' }}：</text>
                    <text style="color: #fa453c" v-if="item.deductCryptocurrency > 0"
                      >{{ item.deductCryptocurrency }}豆+
                    </text>
                    <text style="color: #fa453c" v-if="item.deductPoint > 0"
                      >{{ item.deductPoint }}积分+
                    </text>
                    <text style="color: #fa453c">¥{{ (item.payPrice * 0.01).toFixed(2) }}</text>
                  </view>
                  <view v-if="item.refundStatus === 0">
                    <view class="btn-group" v-if="item.status === 0">
                      <view class="solid-btn btn" @click.stop.prevent="onPay(item)"> 立即支付</view>
                      <view @click.stop.prevent="onOrderCancel(item)" class="warning-btn btn">
                        取消订单
                      </view>
                    </view>
                    <view
                      @click.stop.prevent="onOrderConfrim(item)"
                      class="btn-group"
                      v-else-if="item.status == 20"
                    >
                      <view class="solid-btn btn" v-if="item.deliveryType == 1"> 立即收货</view>
                      <view
                        @click.stop.prevent="onOrderDetail(item)"
                        class="solid-btn btn"
                        v-if="item.deliveryType == 4"
                      >
                        去核销
                      </view>
                      <view
                        @click.stop.prevent="onExpress(item)"
                        v-if="item.deliveryType == 1 && item.status == 10"
                        class="hollow-btn btn"
                      >
                        查看物流
                      </view>
                    </view>
                    <view
                      class="btn-group"
                      v-else-if="(item.status == 30 || item.status == 10) && item.deliveryType == 1"
                    >
                      <view
                        class="solid-btn btn"
                        @click.stop.prevent="toComment(item)"
                        v-if="item.status == 30 && !item.commentStatus"
                      >
                        立即评价
                      </view>
                      <view class="btn hollow-btn" @click.stop.prevent="onExpress(item)">
                        查看物流
                      </view>
                    </view>
                    <view class="btn-group" v-else-if="item.status == 10 && item.deliveryType == 4">
                      <view @click.stop.prevent="onClerk(item)" class="solid-btn btn"> 去核销</view>
                    </view>
                    <view class="btn-group" v-else-if="item.status == 40">
                      <view @click.stop.prevent="onDelete(item)" class="danger-btn btn">
                        立即删除
                      </view>
                    </view>
                    <view class="btn-group" v-else>
                      <view class="hollow-btn btn"> 查看详情</view>
                    </view>
                  </view>
                  <view v-else>
                    <view class="btn-group">
                      <view class="hollow-btn btn" @click.stop.prevent="onReturnDetail(item)">
                        售后详情
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </z-paging>
        </swiper-item>
      </swiper>
    </z-paging-swiper>

    <PayPopup ref="payPopupRef" @close="closePay">
      <p style="font-size: 50rpx; font-weight: 600; padding: 20rpx; text-align: center">
        ¥{{ realPay }}
      </p>
    </PayPopup>
    <u-popup
      :closeable="true"
      close-icon-pos="top-left"
      v-model="show2"
      mode="bottom"
      height="auto"
      border-rad
      border-radius="15"
    >
      <view class="popup-box">
        <view class="popup-title"> 发表评论</view>

        <view class="goods-start">
          <text>商品评价</text>
          <view class="start-bar">
            <u-rate size="50" active-color="#FBC258" v-model="form.scores"></u-rate>
          </view>
        </view>

        <view class="">
          <view class="">
            评论内容
            <text style="color: #999999">（至少15字以上）</text>
          </view>
          <textarea
            v-model="form.content"
            style="width: 100%; height: 120rpx; margin: 15rpx 0; font-size: 28rpx"
            name=""
            placeholder="商品满足您的期待吗？说说它的优点和美中不足吧。"
            id=""
            cols="50"
            rows="20"
          ></textarea>
        </view>

        <view class="image-group">
          <view class="">
            图片
            <text style="color: #999999">（{{ fileList ? fileList.length : 0 }}/3）</text>
          </view>
          <view class="" style="margin-top: 20rpx">
            <u-upload
              :custom-btn="true"
              :action="action"
              max-count="3"
              ref="uUpload"
              :file-list="fileList"
              :before-upload="beforeFileUpload"
              @on-remove="onFileRemove"
            >
              <view
                slot="addBtn"
                class="slot-btn"
                hover-class="slot-btn__hover"
                hover-stay-time="150"
              >
                <u-icon name="/static/xj.png" size="80"></u-icon>
                <view style="color: #999999">添加照片</view>
              </view>
            </u-upload>
          </view>
        </view>
        <view class="" style="margin-bottom: 100rpx"></view>

        <view class="fixed-wapper">
          <view class="submit-btn" @click="pushComment"> 提交评价</view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import PayPopup from '@/components/PayPopup.vue'
import { BASE_URL, UP_URL } from '@/common/config'

export default {
  components: {
    PayPopup
  },
  data() {
    return {
      action: BASE_URL + UP_URL,
      imgStyle: {
        width: '12rem'
      },
      fileList: [],
      show2: false,
      payOrderId: '',
      current: 0,
      scurrent: 0,
      realPay: '',
      resStatus: '',
      tabsList: [
        {
          name: '全部',
          key: ''
        },
        {
          name: '待付款',
          key: 'payment'
        },
        {
          name: '进行中',
          key: 'doing'
        },
        // {
        //   name: '待发货',
        //   key: 'deliver',
        // },
        // {
        //   name: '待收货',
        //   key: 'receive',
        // },
        // {
        //   name: '待核销',
        //   key: 'clerk',
        // },
        {
          name: '已完成',
          key: 'complete'
        },
        {
          name: '退款/售后',
          key: 'return'
        }
      ],
      itemList: [[], [], [] /*, [], []*/, [], []],
      form: {
        content: '',
        scores: 5,
        descriptionScores: 5,
        benefitScores: 5,
        orderId: null,
        picUrls: []
      },
      order_id: ''
    }
  },
  onLoad(res) {
    if (res.index) {
      this.current = Number(res.index) ? Number(res.index) : 0
      this.scurrent = Number(res.index) ? Number(res.index) : 0
    }
    if (res.status) {
      let _index = this.tabsList.findIndex((item) => item.key == res.status)
      console.log(_index, res.status)
      this.current = _index ? _index : 0
      this.scurrent = _index ? _index : 0
    }
  },

  onShow() {
    this.queryList(1)
  },
  methods: {
    tabsChange(index) {
      this.scurrent = index
      this.queryList(1)
    },
    transition(e) {
      let dx = e.detail.dx
      this.$refs.uTabs.setDx(dx)
    },
    animationfinish(e) {
      this.current = e.detail.current
      this.scurrent = e.detail.current
      this.$refs.uTabs.setFinishCurrent(this.scurrent)
      if (this.itemList[this.current].length == 0) {
        this.queryList(1)
      }
      // console.log('animationfinish',this.current,this.scurrent)
    },
    queryList(pageNo = 1, pageSize = 10) {
      if (pageNo === 1) {
        this.itemList[this.scurrent] = []
      }
      this.$u
        .get('/app-api/trade/order/page', {
          pageNo,
          pageSize,
          orderStatus: this.tabsList[this.scurrent].key
        })
        .then((res) => {
          this.$refs.paging[this.scurrent].complete(res.data.list)
        })
    },
    onPay(e) {
      this.payOrderId = e.no
      this.realPay = (e.payPrice * 0.01).toFixed(2)
      this.$refs.payPopupRef.open(this.payOrderId), '', e.payPrice === 0
    },
    closePay() {
      this.queryList(1)
    },
    toComment(item) {
      this.form.orderId = item.id
      this.show2 = true
    },
    beforeFileUpload(_index, list) {
      this.fileList = list
    },
    onFileRemove(_index, list) {
      this.fileList = list
    },
    pushComment() {
      let self = this
      self.$refs.uUpload.lists.forEach((val) => {
        self.form.picUrls.push(val.response.data)
      })
      if (self.form.scores == 0) {
        self.$u.toast('评价最低为1分')
        return
      }
      if (self.form.content == '') {
        self.$u.toast('请输入评价内容')
        return
      }
      self.$u.post('/app-api/product/comment/create', self.form).then((res) => {
        if (res.code === 0) {
          self.form.content = ''
          self.form.scores = 5
          self.form.orderId = null
          self.form.picUrls = []
          self.$u.toast('评价成功')
          setTimeout(function () {
            self.show2 = false
          }, 800)
        } else {
          self.$u.toast(res.msg)
        }
      })
    },
    onOrderCancel(item) {
      let self = this
      uni.dialog.confirm('温馨提示', '确定要取消订单吗？', () => {
        self.$u.get('/app-api/trade/order/cancel?id=' + item.id).then((res) => {
          self.$u.toast('取消成功')
          setTimeout(() => {
            this.queryList(1)
          }, 500)
        })
      })
    },
    onOrderConfrim(item) {
      let self = this
      uni.dialog.confirm('温馨提示', '该订单确认收货吗？', () => {
        // self.$api.putOrderReceive({id:item.id}).then(res => {
        // 	self.$u.toast('收货成功');
        // 	setTimeout(() => {
        // 		this.queryList(1)
        // 	}, 500)
        // });
        self.$u.post('/app-api/trade/order/receive?id=' + item.id).then((res) => {
          self.$u.toast('收货成功')
          setTimeout(() => {
            this.queryList(1)
          }, 500)
        })
      })
    },
    onResellPush(item) {
      this.$utils.route({
        url: '/goods/resell-push/resell-push',
        params: {
          id: item.id
        }
      })
    },
    onPushComment(item) {
      this.$utils.route({
        url: '/other/push-comment/push-comment',
        params: {
          id: item.id
        }
      })
    },
    onOrderDetail(item) {
      this.$utils.route({
        url: '/goods/order-details/order-details',
        params: {
          id: item.id
        }
      })
    },
    onReturnDetail(item) {
      this.$utils.route({
        url: '/goods/order-details/order-refund-details',
        params: {
          id: item.id
        }
      })
    },
    onExpress(e) {
      uni.navigateTo({
        url:
          '/other/express-process/express-process?id=' +
          e.id +
          '&goodsJson=' +
          JSON.stringify(e.items[0])
      })
    },
    onClerk(item) {
      if (item.qrcode) {
        uni.setStorageSync('verify_qrcode', item.qrcode)
      }
      this.$utils.route('/goods/order-qrcode/order-qrcode?verifyCode=' + item.verifyCode)
    },
    onDelete(item) {
      let self = this
      uni.dialog.confirm('温馨提示', '该订单确认删除吗？', () => {
        self.$u.get('/app-api/trade/order/delete?id=' + item.id).then((res) => {
          self.$u.toast('删除成功')
          setTimeout(() => {
            this.queryList(1)
          }, 500)
        })
      })
    },
    onShop(e) {
      uni.navigateTo({
        url: '/other/merchant-center/merchant-center?id=' + e.id
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import url('order-list.css');
@import url('@/style/btn.css');

.slot-btn {
  width: 200rpx;
  height: 200rpx;
  background: #f5f5f5;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-flow: column;
}
</style>
